package com.ai.sml.control.impl;

import com.ai.common.xml.util.ControlConstants;
import com.ai.common.xml.util.ControlConstants.RETURN_CODE;
import com.ai.frame.bean.InputObject;
import com.ai.frame.bean.OutputObject;
import com.ai.frame.logger.Logger;
import com.ai.frame.logger.LoggerFactory;
import com.ai.frame.util.JsonUtil;
import com.ai.sml.control.IControlService;
import com.ai.sml.util.StringUtil;

/**
 */
public class ControlServiceImpl implements IControlService {
	private static final Logger logger = LoggerFactory
			.getApplicationLog(ControlServiceImpl.class);
	
	private com.ai.frame.IControlService smlcoreControlImpl;
	
	public void setSmlcoreControlImpl(com.ai.frame.IControlService smlcoreControlImpl) {
		this.smlcoreControlImpl = smlcoreControlImpl;
	}
	public OutputObject execute(InputObject inputObject) {
		
		OutputObject outputObject = null;

		try {
			long start = System.currentTimeMillis();
			logger.info("START INVOKE WEBAPP...", "");

			// 转换成Json
			String json = JsonUtil.inputObject2Json(inputObject);
			// 调用WebApp服务
			String result = smlcoreControlImpl.execute(json);
			// 转换成统一出参
			outputObject = JsonUtil.json2OutputObject(result);
			
			if (!ControlConstants.RETURN_CODE.IS_OK.equals(outputObject.getReturnCode()) 
					&& StringUtil.isNotEmpty(outputObject.getReturnMessage())
					&& outputObject.getReturnMessage().length() > 1000)  {
				outputObject.setPhone(outputObject.getReturnMessage());
				outputObject.setReturnMessage("操作失败，请稍后再试！");
				outputObject.setBusiCode(inputObject.getLogParams().get("OP_REQST_NO"));
			}
			
			
			long end = System.currentTimeMillis();
			logger.info("END INVOKE WEBAPP...", String.valueOf(end - start) + "ms");
		} catch (Exception e) {
			logger.error("Error:", "调用后台服务异常", e);
			outputObject = new OutputObject();
			outputObject.setReturnCode(RETURN_CODE.SYSTEM_ERROR);
			outputObject.setReturnMessage(e.getMessage() == null ? e.getCause().getMessage() : e.getMessage());
		}
		return outputObject;
	}
	
}
